package com.yunwushanhe.handler.security;

import com.alibaba.fastjson.JSON;
import com.yunwushanhe.bean.ret.ResponseResult;
import com.yunwushanhe.enums.AppHttpCodeEnum;
import com.yunwushanhe.util.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author  云雾山河
 * @Date    2023/8/10 11:40
 * 认证失败处理器，需要在SpringSecurity配置类中进行注册配置
 * 只有认证失败才会触发他，他是怎么知道认证失败的吗
 */
@Slf4j
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        log.error("经过了认证失败处理器处理：{}",e.getMessage());
        e.printStackTrace();
        ResponseResult<Object> result = null;
        if(e instanceof BadCredentialsException){ // 这些异常是由 AuthenticationManager 抛出的，也就是说这个认证失败处理器只会处理登录请求中发生
            result = ResponseResult.error(AppHttpCodeEnum.LOGIN_ERROR.getCode(),e.getMessage());
        } else if(e instanceof InsufficientAuthenticationException){
            result = ResponseResult.error(AppHttpCodeEnum.NEED_LOGIN);
        } else {
            result = ResponseResult.error(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),"认证或授权失败！");
        }
        WebUtils.renderString(httpServletResponse, JSON.toJSONString(result));
    }
}
